package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class HandlerValidException {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validateBrandException(MethodArgumentNotValidException e){
      //log.error("异常信息:{}----异常类型:{}",e.getMessage(),e.getClass());
        Map<String,String> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(item->{
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            map.put(field,defaultMessage);
        });
      return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R otherBrandException(Throwable e){
        //log.error("异常信息:{}----异常类型:{}",e.getMessage(),e.getClass());

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
